package com.codefish.codefish_blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codefish.codefish_blog.entity.CommentRecord;
import com.codefish.codefish_blog.entity.User;
import com.codefish.codefish_blog.mapper.CommentRecordMapper;
import com.codefish.codefish_blog.service.CommentRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.codefish.codefish_blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author codefish
 * @since 2022-03-22
 */
@Service
public class CommentRecordServiceImpl extends ServiceImpl<CommentRecordMapper, CommentRecord> implements CommentRecordService {
    @Autowired
    UserService userService;

    @Override
    public List<List<CommentRecord>> loadArticleComments(Long articleId) {
        QueryWrapper<CommentRecord> wrapper = new QueryWrapper<>();
        wrapper.eq("article_id", articleId);
        //获取相关评论
        List<CommentRecord> list = this.list(wrapper);
        //组织一级和二级评论
        Map<Long, List<CommentRecord>> map = new HashMap<>(2 << 4);
        list.forEach(
                (item) -> {
                    //为给个评论匹配用户名
                    User user = userService.getById(item.getOwnerId());
                    item.setOwnerName(user.getUsername());
                    //key不存在则new一个list
                    map.computeIfAbsent(item.getPid(), key -> new ArrayList<>());
                    //以上代码保证了key的存在
                    map.get(item.getPid()).add(item);
                }
        );
        //生成二级列表
        List<List<CommentRecord>> rlist = new ArrayList<>();
        for (Long pid : map.keySet()) {
            rlist.add(map.get(pid));

        }
        //返回二级列表
        return rlist;
    }

    @Override
    public void addCommentOnArticle(long articleId, String content, int ownerId) {
        CommentRecord record = new CommentRecord();
        record.setOwnerId(ownerId);
        record.setArticleId(articleId);
        record.setContent(content);
        //数据库插入评论记录
        this.save(record);
        //一级评论，该评论的父评论id和当前id相同
        CommentRecord updateRecord = new CommentRecord();
        updateRecord.setId(record.getId());
        updateRecord.setPid(record.getId());
        this.updateById(updateRecord);
    }

    @Override
    public void replyComment(long articleId, long commentId, String content, int ownerId) {
        CommentRecord record = new CommentRecord();
        record.setOwnerId(ownerId);
        record.setArticleId(articleId);
        record.setPid(commentId);
        record.setContent(content);
        //数据库插入回复评论记录
        this.save(record);
    }
}
